#include<iostream>
#include<unistd.h>
#include<cstdio>
#include<cassert>
#include<cstring>
#include<sys/wait.h>
#define MAX 1024

using namespace std;

int main()
{
    //建立管道
    int pipefd[2]={0};
    int n=pipe(pipefd);
    assert(n==0);
    //防止报警
    (void)n;
    cout <<"piped[0]: "<<pipefd[0]<<"  "<<"pipefd[1]: "<<pipefd[1]<<endl;

    //2.创建子进程
    pid_t id=fork();
    if(id<0)
    {
        perror("fork");
        return -1;
    }

    //父亲读 孩子写
    if(id==0){
        close(pipefd[0]);

        //写数据
        int cnt=0;
        while(true)
        {
            //往缓冲区写
            char message[MAX];
            snprintf(message,sizeof(message),"hellow I am child,pid: %d, cnt :%d",getpid(),cnt);
            cnt++;

            //写入文件
            write(pipefd[1],message,strlen(message));

            sleep(1);
        }

        // 进程退出 管道会自动关闭
        cout<<"child close......"<<endl;
        exit(0);

    }


    //父进程，关闭 读取
    close(pipefd[1]);

    char buffer[MAX];
    while(true)
    {
        ssize_t n =read(pipefd[0],buffer,sizeof(buffer)-1);
        
        //读取的内容当作字符串处理
        if(n>0)
        {
            buffer[n]='\0';
            cout<<"I am father,child say "<<buffer<<" to me!"<<endl;

        }
        //写端结束，读到0
        else if(n==0)
        {
            cout<<"child exit ,me too!";
            break;
        }
        cout<<"father return val: "<<n<<endl;
        sleep(1);
        // break;
    }
    cout<<"read point clese"<<endl;
    close(pipefd[0]);

    //等待回收子进程
    sleep(5);
    int status=0;
    pid_t rid =waitpid(id, &status,0);
    if(rid ==id)
    {
        cout<<"wait success,child exit sin: "<<(status&0X7F)<<endl;
    }

    return 0;
}
